package com.techshine.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.techshine.common.page.Page;
import com.techshine.entity.Baoming;
import com.techshine.entity.Info;
import com.techshine.service.BaomingService;
import com.techshine.service.InfoService;
import com.techshine.util.EhcacheUtil;
import com.techshine.util.HttpClintUtil;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller
@RequestMapping(value="/baoming")
public class BaoMingController {
    @Resource
    BaomingService baomingService;

    @Resource
    InfoService infoService;


   @Value("${appId}")
    private  String appId;

    @Value("${appSecret}")
    private  String appSecret;












    @ResponseBody
    @RequestMapping(value = "test",method = RequestMethod.GET)
    public String test(){
        System.out.println("spring boot test");
        return "spring boot   ......ggggaaaa";
    }



    @ResponseBody
    @RequestMapping(value = "haikang")
    public Map<String,Object> haikang(@RequestBody Map<String,Object> map){


        System.out.println("haikang boot test");


        System.out.println(map);
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            String json = objectMapper.writeValueAsString(map);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }




        Map<String,Object> map2=new HashMap<>();

        map2.put("HTTP/1.1",200);



        return map2;
    }





    @ResponseBody

    public class JsonController {

        @RequestMapping(value = "/json", consumes = MediaType.APPLICATION_JSON_VALUE)
        public  Map<String,Object> processJson(@RequestBody String json) {








            System.out.println(json);



            Map<String,Object> map2=new HashMap<>();

            map2.put("HTTP/1.1",200);



            return map2;
        }
    }









    @ResponseBody
    @RequestMapping(value = "test2",method = RequestMethod.GET)
    public String test2(){
        System.out.println("spring boot testtest2test2");
        return "spring boot   ......test2test2test2test2";
    }

    @RequestMapping("/aa")
    public String aa(HttpServletRequest request) {
        System.out.println("aaa好aaa");
        request.setAttribute("a","aa");
        return "aa";
    }

    @RequestMapping("/index")
    public String main(HttpServletRequest request) {
        return "bishengbei";
    }



    @RequestMapping("/zhuce")
    public String zhuce(HttpServletRequest request) {
        return "zhuce";
    }






    @RequestMapping("/bishengbei")
    public Object  bishengbei(String   code ,  String  state)   {
        Map<String,String> resultMap=new HashMap<>();


        System.out.println("code---"+code);
        System.out.println("state---"+state);



        String  openid = getOpenId(code);


        System.out.println("openid---"+openid);


        ModelAndView mv = new ModelAndView();
        //将数据放入对象中
        mv.addObject("openid", openid);


        mv.setViewName("bishengbei");
        //返回ModelAndView对象


        return mv;


    }










    @ResponseBody
    @RequestMapping("/fasong")
    public Map<String, String> fasong() {
        Map<String,String> resultMap=new HashMap<>();




        String accessToken = getToken();


        System.out.println("token---"+accessToken);


        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;



        String str1="三木";
        String str2="毕昇杯";

        // 定义JSON数据
        String jsonInputString = "{" +
                "\"touser\":\"octMN1dyhqPld8IhouzI7_6diFLU\"," +
                "\"template_id\":\"1Tj3iPebqezaEzNObqYMnvUHUIFAKXa4wc-FOkGjhBw\"," +
                "\"url\":\"https://sp1.penevision.com/userlook?id=2\"," +
                "\"data\":{" +
                "\"thing4\":{" +
                "\"value\":\""+str1+"\"" +
                "}," +
                "\"thing1\":{" +
                "\"value\":\"毕昇杯\"" +
                "}" +
                "}" +
                "}";

        System.out.println("jsonInputString--"+jsonInputString);


        try {
            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setDoOutput(true);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            System.out.println("Response code: " + responseCode);




            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                System.out.println("Response JSON: " + response.toString());
            } else {
                System.out.println("Failed to get JSON response. Response code: " + responseCode);
            }




            resultMap.put("response",String.valueOf(responseCode));





        } catch (Exception e) {
            e.printStackTrace();
        }



















        resultMap.put("status","200");



        return resultMap;


    }




    private void fasaongxiaoxi(String openid, String stuname,Integer  id) {




        String accessToken = getToken();


        System.out.println("token---"+accessToken);


        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;



        String str1=stuname;
        String str2="毕昇杯";

        // 定义JSON数据
        String jsonInputString = "{" +
                "\"touser\":\""+openid+"\"," +
                "\"template_id\":\"1Tj3iPebqezaEzNObqYMnvUHUIFAKXa4wc-FOkGjhBw\"," +


                "\"url\":\"http://sp1.penevision.com/userlook?id="+id+"\"," +



                "\"data\":{" +
                "\"thing4\":{" +
                "\"value\":\""+str1+"\"" +
                "}," +
                "\"thing1\":{" +
                "\"value\":\"毕昇杯\"" +
                "}" +
                "}" +
                "}";

        System.out.println("jsonInputString--"+jsonInputString);


        try {
            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setDoOutput(true);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            System.out.println("Response code: " + responseCode);




            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                System.out.println("Response JSON: " + response.toString());
            } else {
                System.out.println("Failed to get JSON response. Response code: " + responseCode);
            }



            System.out.println("发送返回--"+   String.valueOf(responseCode));






        } catch (Exception e) {
            e.printStackTrace();
        }










    }




    @ResponseBody
    @RequestMapping("/getToken")
    public String  getToken() {



        //  Map<String,String> resultMap=new HashMap<>();

        Cache cache = EhcacheUtil.getScanCache();






        System.out.println("开始获取签名缓存");

        String tokenS="";



        Element access_token = cache.get("access_token");

        if(access_token==null){


            System.out.println("未找到签名--重新获取");


            String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;

            System.out.println(url);
            Map<String,Object>   map = HttpClintUtil.getUrlString(url);

            // 打印Map中的键值对
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
            }


            tokenS=(String) map.get("access_token");



            //  缓存


            Element element1 = new Element("access_token", tokenS);


            // 将元素添加到缓存
            cache.put(element1);




        }else{



            tokenS=(String)access_token.getObjectValue();

        }






        return tokenS;








    }








    @ResponseBody
    @RequestMapping("/getOpenId")
    public String  getOpenId(String code)   {


        String openId="";

        // Cache cache = EhcacheUtil.getScanCache(resourceUrl);

        System.out.println("开始获取网页授权access_token缓存");



/*

        Element wy_openId = cache.get("wy_openId");

        if(wy_openId==null) {
*/




        String url ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxf6959f287a25eca1&secret=44e12d4f535df037b3f25daf88952246&code="+code+"&grant_type=authorization_code";





        System.out.println(url);



        //  String codeEncoded = URLEncoder.encode(url, StandardCharsets.UTF_8.toString());



        Map<String, Object> map = HttpClintUtil.getUrlString(url);

        // 打印Map中的键值对
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }


        openId = (String) map.get("openid");




        //  缓存


        //    Element element1 = new Element("wy_openId", openId);


        // 将元素添加到缓存
        //    cache.put(element1);


   /* }else{



            openId=(String)wy_openId.getObjectValue();

    }
*/






        return openId;








    }









    private static String createNonceStr() {
        return UUID.randomUUID().toString();
    }


    private static String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }




    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }



    private static final String TOKEN = "lsls"; // 在微信公众平台配置的Token


    @ResponseBody
    @RequestMapping("/wechat")
    public String validate(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        if (StringUtils.isEmpty(signature) || StringUtils.isEmpty(timestamp)
                || StringUtils.isEmpty(nonce) || StringUtils.isEmpty(echostr)) {
            return "Invalid request";
        }

        String[] arr = new String[]{TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            sb.append(s);
        }

        String result = sha1(sb.toString());
        if (result.equals(signature)) {
            return echostr;
        } else {
            return "Invalid signature";
        }
    }

    private String sha1(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] bytes = digest.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }














    @ResponseBody
    @RequestMapping("/selectById")
    public Map<String,Object> selectById(Integer id) {

        Map<String,Object> map=new HashMap<>();

        Baoming baoming=    baomingService.selectByPrimaryKey(id);

        map.put("status",200);

        map.put("baoming",baoming);

        return map;




    }



    @RequestMapping("/insertBaoming")
    public String insertBaoming(Baoming baoming) {



        baoming.setDate(new Date());
        baoming.setStatus("0");

        try {
            baomingService.insertSelective(baoming);
        } catch (Exception e) {
            //    e.printStackTrace();
        }


        return "success";




    }



    @RequestMapping("/allxinxi")
    public String allxinxi() {
        return "selectallbaoming";


    }









    @RequestMapping("/xiangqing")
    public Object  xiangqing(Integer   id   )   {
        Map<String,String> resultMap=new HashMap<>();


        System.out.println("id---"+id);




        ModelAndView mv = new ModelAndView();
        //将数据放入对象中
        mv.addObject("id", id);


        mv.setViewName("xiangqing");
        //返回ModelAndView对象


        return mv;


    }









    @RequestMapping("/userlook")
    public Object  userlook(Integer   id   )   {
        Map<String,String> resultMap=new HashMap<>();


        System.out.println("id---"+id);




        ModelAndView mv = new ModelAndView();
        //将数据放入对象中
        mv.addObject("id", id);


        mv.setViewName("userlook");
        //返回ModelAndView对象


        return mv;


    }









    @ResponseBody
    @RequestMapping("/shenhetongguo")
    public  Map<String,Object> shenhetongguo(Integer  id) {

        Map<String,Object> map =new HashMap<>();


        Baoming baoming=  baomingService.selectByPrimaryKey(id);

        String openid=baoming.getOpenid();

        String fuzename=baoming.getFuzerenname();

        System.out.println("获得openid---"+openid);
        System.out.println("获得stuname---"+fuzename);

        fasaongxiaoxi(openid,fuzename,id);



        Baoming baoming1=new Baoming();

        baoming1.setId(id);
        baoming1.setStatus("1");
        baomingService.updateByPrimaryKeySelective(baoming1);

        map.put("status",200);


        return  map;
    }


    @ResponseBody
    @RequestMapping("/shenhebohui")
    public  Map<String,Object> shenhebohui(Integer  id) {

        Map<String,Object> map =new HashMap<>();



        Baoming baoming1=new Baoming();

        baoming1.setId(id);
        baoming1.setStatus("2");
        baomingService.updateByPrimaryKeySelective(baoming1);

        map.put("status",200);


        return  map;
    }

    @ResponseBody
    @RequestMapping("/selectallbaoming")
    public Map<String,Object> selectallbaoming(Baoming baoming , Page page) {


        Map<String,Object> map =new HashMap<>();


        baoming.setPage(page);







        List<Baoming> list2= baomingService.selectList(baoming);


        Integer  currtpage= page.getCurrentPage();

        Integer  pagesize= page.getShowCount();

        if(pagesize==null){

            pagesize=10;
        }


        if(currtpage==null){

            currtpage=1;
        }








        int start =   ( currtpage-1)*pagesize;

        int end =   currtpage*pagesize ;

        page.setTotalResult(list2.size());


        int  yushu=list2.size()%pagesize;

        if(yushu==0){
            page.setTotalPage(list2.size()/pagesize);

        }else{

            page.setTotalPage(list2.size()/pagesize+1);


        }

        page.setCurrentPage(currtpage);
        page.setShowCount(pagesize);


        baoming.setStart(start);

        baoming.setEnd(end);
        List<Baoming>  list= baomingService.selectByPage(baoming);




        map.put("result",list);

        map.put("status",200);

        map.put("page",page);
        return  map;



    }








    @ResponseBody
    @RequestMapping("/selectInfo")
    public Map<String,Object> selectInfo() {

        Map<String,Object>   map=new HashMap<>();


        Info info=null;
        try {
            info= infoService.selectByPrimaryKey("zhuceparam");
        } catch (Exception e) {





        }


        map.put("status","200");

        map.put("info",info);

        return map;



    }

}
